<?php

namespace app\api\controller;

use app\common\Aliyun\demo\SendSms;
use app\common\library\common;
use think\db\exception\DataNotFoundException;
use think\facade\Db;
use think\Request;
use think\Response;


class Seatnotify extends Wap
{

    /**
     * @param Request $request
     * @return void
     */
    public function index(Request $request)
    {
        if (request()->isPost()) {
            // 获取微信回调的数据
            $notifiedData = file_get_contents('php://input');

            //XML格式转换
            $xmlObj = simplexml_load_string($notifiedData, 'SimpleXMLElement', LIBXML_NOCDATA);
            $xmlObj = json_decode(json_encode($xmlObj), true);
            $sign_return = $xmlObj['sign'];

            //支付成功
            if ($xmlObj['return_code'] == "SUCCESS" && $xmlObj['result_code'] == "SUCCESS") {
                unset($xmlObj['sign']);
                $wxapp = Db::name('mini_match')->where('id', 1)->find();
                if ($wxapp['app_id'] && $wxapp['wc_hid'] && $wxapp['api_key']) {
                    $key = $wxapp['api_key'];
                }
                $sign = $this->appgetSign($xmlObj, $key);

                if ($sign === $sign_return) {
                    $order = Db::name('customer_seat_order')->where('order_on', $xmlObj['out_trade_no'])->find();
                    if ($order['pay_time'] > 0) {
                        $this->returnCode(true, 'OK');
                    }
                    $order['pay_time'] = time();
                    $order['status'] = 1;
                    $order['transaction_id'] = $xmlObj['transaction_id'];
                    // 摇号
                    $orderinfo = Db::name('customer_seat_order')->where('status', 'in', [0, 1, 2])->where('store_id', $order['store_id'])->group('house_id')->select();

                    $orderdata = Db::name('customer_seat_order')->where('status', 'in', [0, 1, 2])->where('store_id', $order['store_id'])->where('order_on', '<>', $order['order_on'])->select();
                    $room = Db::name('customer_house')->where('store_id', $order['store_id'])->where('mark', 1)->select();
                    $orderList = Db::name('customer_seat_order')->where('seat_id', $order['seat_id'])->where('happy_id', $order['happy_id'])->where('method_id', $order['method_id'])->where('order_on', '<>', $order['order_on'])->where('status', 'in', [0, 1, 2])->count();


                    $course = Db::name('customer_seat')->where('id', $order['seat_id'])->find();
                    $info = Db::name('mini_happy')->where('id', $course['happy_id'])->find();
                    $course['num'] = $info['num'];

                    for ($i = 1; $i <= $course['num']; $i++) {
                        $k[] = $i;
                    }
                    $room_list_id = array();
                    if (count($orderinfo) > 0) {
                        foreach ($orderinfo as $i => $v) {
                            $room_list_id[] = $v['house_id'];
                        }
                    }
                    $room_id = array();

                    if ($orderList >= $course['num']) {
                        if ($orderList % $course['num'] != 0) {
                            $orderListdata = Db::name('customer_seat_order')->where('order_on', '<>', $order['order_on'])->where('seat_id', $order['seat_id'])->where('happy_id', $order['happy_id'])->where('method_id', $order['method_id'])->where('status', 'in', [0, 1, 2])->group('house_id')->select();
                            foreach ($orderListdata as $i => $v) {
                                $count = Db::name('customer_seat_order')->where('order_on', '<>', $order['order_on'])->where('seat_id', $order['seat_id'])->where('happy_id', $order['happy_id'])->where('method_id', $order['method_id'])->where('status', 'in', [0, 1, 2])->where('house_id', $v['house_id'])->count();
                                if ($count < $course['num']) {
                                    $house_id = $v['house_id'];
                                    $lotterydata[] = intval($v['lottery']);
                                }
                            }

                            foreach ($k as $i => $v) {

                                if (in_array($v, $lotterydata)) {
                                    unset($v[$i]);
                                } else {
                                    $ki[] = $v;
                                }
                            }
                            $lottery = $ki[array_rand($ki)];
                        } else {
                            // 随机房间号

                            // 记录保洁
                            if (count($room_list_id) > 0) {
                                foreach ($room_list_id as $i => $v) {
                                    $roomda = Db::name('mini_room_list')->where('id', $order['store_id'])->find();
                                    if ($roomda['time'] > 0) {
                                        $datac['order_on'] = $order['order_on'];
                                        $datac['add_time'] = $order['end_time'];
                                        $datac['end_time'] = $order['end_time'] + $roomda['time'] * 60;
                                        $datac['seat_id'] = $v;
                                        $datac['store_id'] = $order['store_id'];
                                        Db::name('customer_order_cleaning')->insert($datac);
                                    }
                                }
                            }

                            foreach ($room as $i => $v) {
                                if (in_array($v['id'], $room_list_id)) {
                                    unset($v[$i]);
                                } else {
                                    $room_id[] = $v['id'];
                                }
                            }
                            if (count($room_id) > 0) {
                                $room_id = $this->arr_to_str($room_id);
                                $list = explode(",", $room_id);

                                $cmax = count($list) - 1;

                                $randnum = mt_rand(0, $cmax);

                                $house_id = $list[$randnum];
                                for ($i = 1; $i <= $course['num']; $i++) {
                                    $k[] = $i;
                                }
                                $lottery = $k[array_rand($k)];
                            }
                        }
                    } else {


                        if ($orderList < $course['num'] && $orderList > 0) {


                            foreach ($orderdata as $i => $v) {
                                $lotterydata[] = intval($v['lottery']);
                                $house_id = $v['house_id'];
                            }

                            foreach ($k as $i => $v) {

                                if (in_array($v, $lotterydata)) {
                                    unset($v[$i]);
                                } else {
                                    $ki[] = $v;
                                }
                            }

                            $lottery = $ki[array_rand($ki)];
                        } else {
                            // 随机房间号
                            foreach ($room as $i => $v) {
                                if (in_array($v['id'], $room_list_id)) {
                                    unset($v[$i]);
                                } else {
                                    $room_id[] = $v['id'];
                                }
                            }


                            if (count($room_id) > 0) {
                                $room_id = $this->arr_to_str($room_id);
                                $list = explode(",", $room_id);

                                $cmax = count($list) - 1;

                                $randnum = mt_rand(0, $cmax);

                                $house_id = $list[$randnum];
                                for ($i = 1; $i <= $course['num']; $i++) {
                                    $k[] = $i;
                                }

                                $lottery = $k[array_rand($k)];
                            }

                        }
                    }
                    $order['house_id'] = $house_id;
                    $order['lottery'] = $lottery;

                    if (Db::name('customer_seat_order')->where('order_on', $xmlObj['out_trade_no'])->update($order)) {
                        if ($room['time'] > 0) {
                            $datac['order_on'] = $order['order_on'];
                            $datac['add_time'] = $order['end_time'];
                            $datac['end_time'] = $order['end_time'] + $room['time'] * 60;
                            $datac['seat_id'] = $order['seat_id'];
                            $datac['store_id'] = $order['store_id'];
                            Db::name('customer_order_cleaning')->insert($datac);
                        }
                        $this->returnCode(true, 'OK');
                    }

                }
            }
        }
    }


    /**
     * 处理数据
     * @param $arr
     * @return bool|string
     */
    public function arr_to_str($arr)
    {
        $t = '';
        foreach ($arr as $v) {
            $temp[] = $v;
        }
        foreach ($temp as $v) {
            $t .= $v . ',';
        }
        $t = substr($t, 0, -1); // 利用字符串截取函数消除最后一个逗号
        return $t;
    }

    /**
     * 回调信息
     * @param $returnCode
     * @param $msg
     * @return void
     */
    private function returnCode($returnCode = true, $msg = null)
    {
        // 返回状态
        $return = [
            'return_code' => $returnCode ? 'SUCCESS' : 'FAIL',
            'return_msg' => $msg ?: 'OK',
        ];
        // 记录日志

        die($this->toXml($return));
    }

    /**
     * @content 格式化参数格式化成url参数  生成签名sign
     * @param $Obj
     * @param $appwxpay_key
     * @return string
     */
    public function appgetSign($Obj, $appwxpay_key)
    {
        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //签名步骤二：在string后加入KEY
        if ($appwxpay_key) {
            $String = $String . "&key=" . $appwxpay_key;
        }
        //签名步骤三：MD5加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        return $result_;
    }


    /**
     * @content 将数组转成uri字符串
     * @param $paraMap
     * @param $urlencode
     * @return false|string
     */
    public function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= strtolower($k) . "=" . $v . "&";
        }
        $reqPar;
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    /**
     * 输出xml字符
     * @param $values
     * @return bool|string
     */
    private function toXml($values)
    {
        if (!is_array($values)
            || count($values) <= 0
        ) {
            return false;
        }

        $xml = "<xml>";
        foreach ($values as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }
}